package atom.core3.security.help;

//客户端证书的颁发
import java.security.Security;
import java.security.cert.Certificate;

import org.bouncycastle.jce.provider.BouncyCastleProvider;


public class MakeCertPfx
{

	private CertInfo caCertInfo;
	private CertInfo userCertInfo;

	private String algorithm = "RSA";
	private String signAlgorithm = "MD5WithRSA";

	public MakeCertPfx()
	{
		// 修改安全通道设置
		Security.addProvider(new BouncyCastleProvider());
	}

	public static void main(String[] args) throws Exception
	{
		MakeCertPfx makeClientCertPfx1 = new MakeCertPfx();

		makeClientCertPfx1.loadCaCertInfo("d:/cert/rootCA.pfx", "ysepay");

		String userIssue = IssueInfo.getIssueInfo("zmc", "ysepay", "organize", "sz", "gd", "cn", "ysepay@126.com");
		makeClientCertPfx1.genClientCert("d:/cert/client1111", "111111", "client1", 3650, userIssue);
		System.out.println("ok");
	}

	public void setAlgorithm(String algorithm, String signAlgorithm)
	{
		this.algorithm = algorithm;
		this.signAlgorithm = signAlgorithm;
	}

	public void loadCaCertInfo(String pfxfileCa, String passwordCa) throws Exception
	{
		caCertInfo = new CertInfo();
		caCertInfo.ReadKeyFromPKCS12(pfxfileCa, passwordCa);

	}

	/**
	 * 
	 * @param username
	 * @param emailaddress
	 */
	// "d:/clientclient" "111111" "aa"
	public void genClientCert(String certFileName, String pfxPassword, String alias, int limitday, String userIssue) throws Exception
	{
		userCertInfo = new CertInfo();
		userCertInfo.CreatPKCS12(caCertInfo, algorithm, signAlgorithm, limitday, userIssue);

		// 产生ｐｆｘ格式CA签名证书
		// 保存用户证书的私钥

		Certificate[] cchain = new Certificate[2];
		cchain[1] = caCertInfo.getCer();
		cchain[0] = userCertInfo.getCer();
		
		CertInfo.SavePrivateKeyCert_PKCS12(cchain,userCertInfo.getPriKey(),certFileName+".pfx",pfxPassword,alias);
		CertInfo.SavePrivateKeyCert_JKS(cchain,userCertInfo.getPriKey(),certFileName+".jks",pfxPassword,alias);
		CertInfo.SavePublicKeyCert(userCertInfo.getCer(),certFileName+".cer");

	}


}
